import os
from typing import Dict, Any, List
import logging
from huggingface_hub import InferenceClient

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class EmotionAnalyzer:
    def __init__(self):
        """
        初始化情感分析器
        使用Hugging Face Inference API进行多语言情感分析
        """
        self.api_key = os.environ.get("HUGGINGFACEHUB_API_TOKEN")
        self.model_name = "tabularisai/multilingual-sentiment-analysis"
        self.client = None
        self._initialize_client()
    
    def _initialize_client(self):
        """初始化Hugging Face客户端"""
        try:
            if not self.api_key:
                raise ValueError("环境变量 HUGGINGFACEHUB_API_TOKEN 未设置")
            
            self.client = InferenceClient(
                provider="hf-inference",
                api_key=self.api_key,
            )
            logger.info("Hugging Face客户端初始化成功")
            
        except Exception as e:
            logger.error(f"客户端初始化失败: {str(e)}")
            self.client = None
    
    def analyze_emotion(self, text: str) -> Dict[str, Any]:
        """
        分析文本情感
        
        Args:
            text: 要分析的文本内容
            
        Returns:
            dict: 包含情感分析结果的字典
        """
        try:
            if not text or not text.strip():
                raise ValueError("文本内容不能为空")
            
            if not self.client:
                raise RuntimeError("Hugging Face客户端未正确初始化")
            
            # 调用Hugging Face API进行情感分析
            result = self.client.text_classification(
                text=text.strip(),
                model=self.model_name,
            )
            
            # 解析结果
            return self._parse_result(result, text)
            
        except Exception as e:
            logger.error(f"情感分析失败: {str(e)}")
            return {
                "success": False,
                "error": str(e),
                "text": text,
                "emotion": None,
                "confidence": 0.0,
                "all_results": []
            }
    
    def _parse_result(self, result: List[Dict], original_text: str) -> Dict[str, Any]:
        """解析Hugging Face API返回的结果"""
        try:
            if not result:
                raise ValueError("API返回结果为空")
            
            # 找到最高分对应的标签
            max_item = max(result, key=lambda x: x.score)
            emotion_label = max_item.label
            confidence = max_item.score
            
            # 映射英文标签到中文
            emotion_map = {
                "positive": "积极",
                "negative": "消极",
                "neutral": "中性"
            }
            chinese_emotion = emotion_map.get(emotion_label.lower(), emotion_label)
            
            # 构建所有结果
            all_results = [
                {"label": item.label, "score": round(item.score, 4)}
                for item in result
            ]
            
            return {
                "success": True,
                "text": original_text,
                "emotion": chinese_emotion,
                "confidence": round(confidence, 4),
                "raw_label": emotion_label,
                "all_results": all_results,
                "model": self.model_name,
                "api_provider": "huggingface"
            }
            
        except Exception as e:
            raise Exception(f"结果解析失败: {str(e)}")
    
    def analyze_batch(self, texts: List[str]) -> List[Dict[str, Any]]:
        """
        批量分析多个文本的情感
        
        Args:
            texts: 文本列表
            
        Returns:
            list: 分析结果列表
        """
        results = []
        for text in texts:
            result = self.analyze_emotion(text)
            results.append(result)
        return results
    
    def get_model_info(self) -> Dict[str, Any]:
        """获取模型信息"""
        return {
            "model_name": self.model_name,
            "provider": "Hugging Face",
            "task": "多语言文本情感分析",
            "supported_emotions": ["积极", "消极", "中性"],
            "supported_languages": ["中文", "英文", "多语言"],
            "features": [
                "云端API调用",
                "多语言支持",
                "置信度评分",
                "批量分析",
                "实时分析"
            ],
            "api_key_required": True,
            "status": "已配置" if self.client else "未配置"
        }
    
    def check_model_status(self) -> Dict[str, Any]:
        """检查服务状态"""
        try:
            if not self.client:
                return {
                    "available": False,
                    "message": "Hugging Face客户端未初始化",
                    "error": "请设置环境变量 HUGGINGFACEHUB_API_TOKEN"
                }
            
            # 测试API连接
            test_result = self.analyze_emotion("测试")
            if test_result["success"]:
                return {
                    "available": True,
                    "message": "Hugging Face情感分析服务可用",
                    "model": self.model_name
                }
            else:
                return {
                    "available": False,
                    "message": test_result.get("error", "API测试失败"),
                    "model": self.model_name
                }
                
        except Exception as e:
            return {
                "available": False,
                "message": f"服务检查失败: {str(e)}",
                "model": self.model_name
            }

# 创建全局实例
emotion_analyzer = EmotionAnalyzer()

def analyze_emotion_api(text: str) -> Dict[str, Any]:
    """
    API接口函数，供Flask调用
    
    Args:
        text: 要分析的文本
        
    Returns:
        dict: 分析结果
    """
    return emotion_analyzer.analyze_emotion(text)

# 测试代码（仅在直接运行文件时执行）
if __name__ == "__main__":
    # 设置测试用的API密钥
    os.environ["HUGGINGFACEHUB_API_TOKEN"] = "your_api_key_here"
    
    # 重新初始化
    analyzer = EmotionAnalyzer()
    
    # 测试单个文本
    test_text = "你喜欢我，我也爱你"
    result = analyzer.analyze_emotion(test_text)
    print("情感分析结果：")
    print(json.dumps(result, ensure_ascii=False, indent=2))
    
    # 测试批量分析
    test_texts = [
        "今天天气真好，我很开心！",
        "这个产品质量太差了，我很失望",
        "一般般吧，没什么特别的"
    ]
    batch_results = analyzer.analyze_batch(test_texts)
    print("\n批量分析结果：")
    for i, res in enumerate(batch_results):
        if res["success"]:
            print(f"文本{i+1}: {res['emotion']} (置信度: {res['confidence']})")
        else:
            print(f"文本{i+1}分析失败: {res['error']}")
